package com.qf.servlet;

import com.qf.service.UserService;
import com.qf.service.serviceImpl.UserServiceImpl;
import com.qf.util.Myutil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 常肖飞先生
 * @version V1.0
 * @Project 0511_3
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 * @Date 2022/5/11 16:35
 */
@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理乱码
        request.setCharacterEncoding("utf-8");
        //接受参数
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        String code = request.getParameter("code");

        HttpSession session = request.getSession();
        String validateCode = (String)session.getAttribute("validateCode");
        //先判断验证码是否为空
        if (Myutil.isEmpty(validateCode)) {
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }
        //判断验证码是否正确
        if (!code.equals(validateCode)) {
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }
        //判断用户名和密码是否为空
        if (Myutil.isEmpty(uname) || Myutil.isEmpty(pwd)) {
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }
        UserService userService = new UserServiceImpl();
        boolean result = userService.login(uname, pwd);

        if (result) {
            session.setAttribute("uname", uname);
            response.sendRedirect(request.getContextPath()+"/bookList");
        } else {
            response.sendRedirect(request.getContextPath()+"/login.html");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
